# @Project: diablo
# @File: update_customer_struct_info
# @Time: 2024/5/20 16:00
# @User: Jolly
# @Email: jolly@007vin.com

"""
修改错乱的结构
"""
import copy

import requests
import datetime
# 小汽配2.0初始化商品定价
# 定价来源：客户提供的excel
from copy import deepcopy

import time
import threading
from queue import Queue

from io import BytesIO
from openpyxl import load_workbook
from pymongo import MongoClient, InsertOne, UpdateOne
from pymongo.errors import ConnectionFailure

lock = threading.Lock()


class UpdateCustomerInfo:

    def __init__(self):

        start_time = time.time()

        # 初始化数据库连接
        # 2.0生产库
        self.diablo_conn_2_0 = self.get_mongo_connection("root", "aa123456", "192.168.191.175", "27017")

        # 执行任务
        self.task()

        print("========= 数据插入,共耗时:{}'s =========".format(round(time.time() - start_time, 3)))

    def get_mongo_connection(self, username, password, host, port):
        try:
            # 创建 MongoClient
            client = MongoClient(f"mongodb://{username}:{password}@{host}:{port}",
                                 maxPoolSize=5,
                                 minPoolSize=1,
                                 maxIdleTimeMS=30000,
                                 waitQueueTimeoutMS=2000)

            # 检测连接是否可用，如果连接不可用则抛出异常
            if not client:
                raise ConnectionFailure("从MongoDB连接池中获取连接失败！")

            return client

        except ConnectionFailure as e:
            # 处理连接失败的异常
            print(f"连接MongoDB失败: {e}")
            return None

    def get_struct_info(self):

        connection = self.diablo_conn_2_0

        try:
            if connection is not None:
                # 执行数据库操作
                db = connection["ddll"]
                conn = db["wechat_repair_shop"]

                filter_dict = {
                    "$or": [
                        {"photo_explanation.license": {
                            "$elemMatch": {
                                "$type": "array"
                            }
                        }},
                        {"photo_explanation.store": {
                            "$elemMatch": {
                                "$type": "array"
                            }
                        }},
                    ]
                }

                docs_count = conn.count_documents(filter_dict)

                if docs_count > 0:

                    docs = conn.find(filter_dict, {'merchant_id': 1, 'name': 1, 'photo_explanation': 1})

                    return docs

        except Exception as e:
            print("获取客户信息列表失败 - mongo：", e)
        finally:
            # 将连接放回连接池
            connection.close()

        return []

    def bulk_operate_agreement_excel(self, bulk_insert_list, bulk_update_list):
        """批量操作 写入、更新等"""

        operate_list = []

        if bulk_insert_list:
            for data in bulk_insert_list:
                operate_list.append(InsertOne(data))

        if bulk_update_list:
            for data in bulk_update_list:
                operate_list.append(UpdateOne(data.get("filter_dict"), data.get("update_dict")))

        # 执行批量更新
        # 获取2.0MongoDB连接
        connection = self.diablo_conn_2_0

        try:
            if connection is not None:
                # 执行数据库操作
                db = connection["ddll"]
                conn = db["wechat_repair_shop"]
                conn.bulk_write(operate_list)

        except Exception as e:
            print("写入2.0MongoDB数据库单据失败：", e)
        finally:
            # 将连接放回连接池
            connection.close()

    # 任务执行
    def task(self):

        # 获取商品
        docs = self.get_struct_info()
        if not docs:
            return

        bulk_insert_list = []
        bulk_update_list = []
        for doc in docs:
            merchant_id = doc.get("merchant_id", "")
            name = doc.get("name", "")
            photo_explanation = doc.get("photo_explanation", {})
            photo_explanation_ = copy.deepcopy(photo_explanation)

            if merchant_id == "":
                continue

            if name == "":
                continue

            if not photo_explanation:
                continue

            license = photo_explanation.get("license", [])
            license_temp = []

            for i in license:
                if isinstance(i, list):
                    for li in i:
                        if li != "":
                            license_temp.append(li)
                else:
                    if i != "":
                        license_temp.append(i)

            photo_explanation["license"] = list(set(license_temp))

            store = photo_explanation.get("store", [])
            store_temp = []

            for i in store:
                if isinstance(i, list):
                    for li in i:
                        if li != "":
                            store_temp.append(li)
                else:
                    if i != "":
                        store_temp.append(i)

            photo_explanation["store"] = list(set(store_temp))

            # 更新数据
            filter_dict = {
                "merchant_id": merchant_id,
                "name": name,
                "is_delete_time": {"$exists": False}
            }

            # 更新操作
            update_dict = {'$set': {
                'photo_explanation': photo_explanation,
                'photo_explanation_': photo_explanation_
            }}

            # 拼入批量列表中
            update_items = {"filter_dict": filter_dict, "update_dict": update_dict}
            bulk_update_list.append(update_items)

        if len(bulk_update_list) > 0:
            try:
                self.bulk_operate_agreement_excel(bulk_insert_list, bulk_update_list)
            except Exception as e:
                print("批量更新客户信息记录失败：", e)


if __name__ == "__main__":
    UpdateCustomerInfo()